package repository

import (
	"RocFamilySystem/models"
	"fmt"
	"gorm.io/gorm"
	"time"
)

type SysPermissionRepository struct {
	Db *gorm.DB
}

func init() {
	registerContainer["SysPermissionRepository"] = &SysPermissionRepository{}
}

func (r *SysPermissionRepository) SetDB(db *gorm.DB) {
	r.Db = db
}

// InsertSysPermission 添加系统系统权限
func (r *SysPermissionRepository) InsertSysPermission(sysPermission *models.SysPermission) {
	//开启事务
	db := r.Db.Begin()
	defer handleTransactional(db)
	now := models.LocalTime(time.Now())
	sysPermission.CreateTime = &now
	err := db.Save(sysPermission).Error
	handleRepositoryErr(err, "添加系统权限失败")
}

// BatchInsertSysPermission 批量添加系统系统权限
func (r *SysPermissionRepository) BatchInsertSysPermission(sysPermissions []models.SysPermission) {
	//开启事务
	db := r.Db.Begin()
	defer handleTransactional(db)
	err := db.Create(&sysPermissions).Error
	handleRepositoryErr(err, "添加系统权限失败")
}

// DeleteSysPermission 删除系统系统权限
func (r *SysPermissionRepository) DeleteSysPermission(sysPermissionId int) {
	db := r.Db.Begin()
	defer handleTransactional(db)

	err := db.Delete(&models.SysPermission{Id: &sysPermissionId}).Error
	handleRepositoryErr(err, "添加系统权限失败")
}

// DeleteSysPermissionBatch 批量删除系统权限
func (r *SysPermissionRepository) DeleteSysPermissionBatch(ids []string) {
	db := r.Db.Begin()
	defer handleTransactional(db)
	err := db.Where("id in (?)", ids).Delete(models.SysPermission{}).Error
	handleRepositoryErr(err, "删除系统缓存失败！")
}

// UpdateSysPermission 修改系统系统权限
func (r *SysPermissionRepository) UpdateSysPermission(sysPermission *models.SysPermission) {
	now := models.LocalTime(time.Now())
	sysPermission.UpdateTime = &now

	err := r.Db.Model(sysPermission).Omit("id", "create_time").Updates(sysPermission).Error
	handleRepositoryErr(err, "修改系统权限失败")
}

// SelectSysPermission 查询系统系统权限
func (r *SysPermissionRepository) SelectSysPermission(sysPermission *models.SysPermission, pageNum, pageSize int) ([]models.SysPermission, int) {
	var (
		list  []models.SysPermission
		total int64
	)
	db := r.Db.Model(&models.SysPermission{})

	if sysPermission != nil {
		if sysPermission.Name != nil {
			db = db.Where("name like ?", fmt.Sprintf("%%%s%%", *sysPermission.Name))
		}
		if sysPermission.Remark != nil {
			db = db.Where("remark like ?", fmt.Sprintf("%%%s%%", *sysPermission.Remark))
		}
		if sysPermission.Method != nil {
			db = db.Where("method == ?", *sysPermission.Method)
		}
	}
	//获取总数
	db.Count(&total)

	//获取列表
	db.Offset(pageSize * pageNum).Limit(pageSize)
	db.Find(&list)

	return list, int(total)
}

// SelectSysPermissionById 查询系统权限通过ID
func (r *SysPermissionRepository) SelectSysPermissionById(id int) models.SysPermission {
	var sysPermission models.SysPermission
	err := r.Db.First(&sysPermission, "id = ?", id).Error
	if err != nil {
		handleRepositoryErr(err, "查询失败")
	}
	return sysPermission
}
